package com.cryptoneedle.center.source.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;

/**
 * 数据源健康检查
 * 在应用启动时检查所有数据源的连接状态
 *
 * @author CryptoNeedle
 * @date 2025-10-31
 */
@Component
public class DataSourceHealthCheck implements ApplicationRunner {

    private static final Logger logger = LoggerFactory.getLogger(DataSourceHealthCheck.class);

    private final DataSource pgDataSource;
    private final DataSource dorisDataSource;
    private final DataSource dolphinDataSource;
    private final JdbcTemplate pgJdbcTemplate;
    private final JdbcTemplate dorisJdbcTemplate;
    private final JdbcTemplate dolphinJdbcTemplate;

    public DataSourceHealthCheck(@Qualifier("pgDataSource") DataSource pgDataSource,
                                 @Qualifier("dorisDataSource") DataSource dorisDataSource,
                                 @Qualifier("dolphinDataSource") DataSource dolphinDataSource,
                                 @Qualifier("jdbcTemplate") JdbcTemplate pgJdbcTemplate,
                                 @Qualifier("dorisJdbcTemplate") JdbcTemplate dorisJdbcTemplate,
                                 @Qualifier("dolphinJdbcTemplate") JdbcTemplate dolphinJdbcTemplate) {
        this.pgDataSource = pgDataSource;
        this.dorisDataSource = dorisDataSource;
        this.dolphinDataSource = dolphinDataSource;
        this.pgJdbcTemplate = pgJdbcTemplate;
        this.dorisJdbcTemplate = dorisJdbcTemplate;
        this.dolphinJdbcTemplate = dolphinJdbcTemplate;
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        logger.info("=== 数据源健康检查开始 ===");

        // 检查PostgreSQL连接
        checkDataSource("PostgreSQL(主数据源)", pgDataSource, pgJdbcTemplate);

        // 检查Doris连接
        checkDataSource("Doris(从数据源)", dorisDataSource, dorisJdbcTemplate);

        // 检查DolphinScheduler连接
        checkDataSource("DolphinScheduler(从数据源)", dolphinDataSource, dolphinJdbcTemplate);

        logger.info("=== 数据源健康检查完成 ===");
    }

    private void checkDataSource(String name, DataSource dataSource, JdbcTemplate jdbcTemplate) {
        try {
            // 测试连接获取
            try (Connection connection = dataSource.getConnection()) {
                logger.info("✅ {} 连接获取成功", name);
                logger.info("   数据库URL: {}", connection.getMetaData().getURL());
                logger.info("   数据库产品: {}", connection.getMetaData().getDatabaseProductName());
                logger.info("   数据库版本: {}", connection.getMetaData().getDatabaseProductVersion());
            }

            // 测试查询执行
            String result = jdbcTemplate.queryForObject("SELECT 1", String.class);
            if ("1".equals(result)) {
                logger.info("✅ {} 查询测试成功", name);
            } else {
                logger.warn("⚠️ {} 查询测试返回异常结果: {}", name, result);
            }

        } catch (Exception e) {
            logger.error("❌ {} 连接测试失败: {}", name, e.getMessage());
        }
    }
}